package controller;

import model.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-27
 * Time：16:14
 */

@WebServlet("/collection")
public class CollectionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        Collection collection = new Collection();
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("用户未登陆，请登录！！");
            return;
        }
        //将user属性从session中取出
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("用户未登陆，请登录！！");
            return;
        }

        String blogId = req.getParameter("blogId");
        //构造following对象
        int uId = user.getUserId();
        collection.setUserId(uId);
        int bId = Integer.parseInt(blogId);
        collection.setBlogId(bId);

        //如果已经收藏，则失败
        CollectionDao collectionDao = new CollectionDao();
        if (!collectionDao.check(collection)) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("你已经收藏过该文章啦！");
            return;
        }

        collectionDao.insert(collection);
        UserDao userDao = new UserDao();
        //更新user信息
        user = userDao.selectById(user.getUserId());
        //更新用户表里的collectionCount字段
        int collectionOrigin = user.getCollectionCount();
        userDao.updateCollectionCount(uId, collectionOrigin+1);

        resp.sendRedirect("blog_detail.html?blogId="+blogId);
    }
}
